

var req;
var parameters;
var url_API = 'http://127.0.0.1:8080/api/';
//var url_API = 'http://ec2-54-200-162-127.us-west-2.compute.amazonaws.com/api/';


function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires = "expires="+d.toGMTString();
document.cookie = cname + "=" + cvalue + "; " + expires;
} 

function getCookie(cname)
{
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
  {
  var c = ca[i].trim();
  if (c.indexOf(name)==0) return c.substring(name.length,c.length);
  }
return "";
} 


function getPublicKey(){
	
	//return getCookie('x-public');//"827ccb0eea8a706c4c34a16891f84e7b";
	if(getCookie('x-public'))
		return getCookie('x-public');
	else
		return "1";
	
}


function getXPrivateKey(){
	
	//return getCookie('x-private');//"202cb962ac59075b964b07152d234b70";
	
	if(getCookie('x-private'))
		return getCookie('x-private');
	else
		return "1";
}


function getURIParameter(key){
	
	var options = decodeURIComponent(window.location.search.slice(1))
                      .split('&')
                      .reduce(function _reduce (/*Object*/ a, /*String*/ b) {
                        b = b.split('=');
                        a[b[0]] = b[1];
                        return a;
                      }, {});
                      
     return options[key];
}


function parseScript(_source) {
		var source = _source;
		var scripts = new Array();
 
		// Strip out tags
		while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
			var s = source.indexOf("<script");
			var s_e = source.indexOf(">", s);
			var e = source.indexOf("</script", s);
			var e_e = source.indexOf(">", e);
 
			// Add to scripts array
			scripts.push(source.substring(s_e+1, e));
			// Strip from source
			source = source.substring(0, s) + source.substring(e_e+1);
		}
 
		// Loop through every script collected and eval it
		for(var i=0; i<scripts.length; i++) {
			try {
				eval(scripts[i]);
			}
			catch(ex) {
				// do what you want here when a script fails
			}
		}
		// Return the cleaned source
		return source;
}




function httpRequest(method, //methodo request 
						strURL, //url
						strParameters, //parameters
						//idElement, //id element html
						eventRetorn ) {//function para retorn status
    
	var HttpReq;
	
	if (window.XMLHttpRequest)
	{// code for IE7+, Firefox, Chrome, Opera, Safari
		HttpReq=new XMLHttpRequest();
	}
	else
	{// code for IE6, IE5
		HttpReq=new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	var tempo = new Date().getTime();
	
	Parameters	=	decodeURIComponent(strParameters);
	       
	if( strParameters =='')
		strParameters ="t="+tempo;
	else
		strParameters = ""+strParameters+ "&t="+tempo;
		
	strParameters	=	strParameters.replace(/%20/g, '+');
		
		
	//if( method == 'GET'){//read data
	//	
	//	HttpReq.open('GET', strURL + strParameters, true);
	//	
	//}
	
	 //Parameters="bruno";
	 
	 
	if ( method == 'POST'){//create data
		
		HttpReq.open('POST', strURL, true);
		strParameters = "parameters="+strParameters;
		
	}else if( method == 'PUT'){//update data
		
		HttpReq.open('PUT', strURL, true);
		strParameters = "parameters="+strParameters;
		
	}else if( method == 'DELETE'){//delete data
		
		HttpReq.open('DELETE', strURL, true);
		strParameters = "parameters="+strParameters;
				
	}else{
		//default
		HttpReq.open('GET', strURL +''+ strParameters, true);
	}
    

	var hash = CryptoJS.HmacMD5( Parameters.toString(), getXPrivateKey());			
	
	
    HttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    HttpReq.setRequestHeader('X-Public', getPublicKey());
    HttpReq.setRequestHeader('X-Hash', hash);
    
    HttpReq.onreadystatechange = function() {
        if (HttpReq.readyState == 4) {
            returnGetRequestHttp(HttpReq.responseText, 
            			//idElement,
            			eventRetorn);
        }
    }
	
	HttpReq.send(strParameters);
		
		
}





function convertToJSON( oObject ){
	
	//var oObject = {} ;
	//oObject["aaa"] = "AAA" ;

    //pluginArrayArg.push(jsonArg1);
    //pluginArrayArg.push(jsonArg2);

//var myJsonString = JSON.stringify(mycars);
	var jsonArray = JSON.parse(JSON.stringify(oObject));
	
	return jsonArray;
//alert("p="+jsonArray.aaa);

//alert(oObject["aaa"]);

//var myJSONText = JSON.stringify(jsonArray);

//alert( myJSONText );


}



function convertToStringJSON( jsonArray ){
	
	//var oObject = {} ;
	//oObject["aaa"] = "AAA" ;

    //pluginArrayArg.push(jsonArg1);
    //pluginArrayArg.push(jsonArg2);

//var myJsonString = JSON.stringify(mycars);
	//var jsonArray = JSON.parse(JSON.stringify(oObject));
	
	//return jsonArray;
//alert("p="+jsonArray.aaa);

//alert(oObject["aaa"]);

	var myJSONText = JSON.stringify(jsonArray);

	return myJSONText;


}


function getInputValueElementId(id){
	return document.getElementById( id ).value;
}






function returnGetRequestHttp(str, eventRetorn){
	

	if(eventRetorn!='' || eventRetorn!=undefined){
		
		var jsonObj	=	convertToJSON(str);
		
		eval( eventRetorn+"("+jsonObj+")");
	}
	
}




function logout() 
{

	var oObject = {} ;
					
	oObject["component"] = "user";
	oObject["controller"] = "user";
	oObject["task"] = "logout";
	
	
	var jsonVales	=	convertToJSON(oObject);
	
	parameters	=	encodeURIComponent(
							convertToStringJSON(jsonVales));
	
	var method='PUT';
	
	//if( getInputValueElementId( "id" ) !=''){ 
		
		//method='PUT';
		
	httpRequest ( method,
					url_API,
					parameters,
					'logountRedirect');
	//}
	
				
	return false;
}


function logountRedirect( jsonObj ){
	
	if( jsonObj.status ==1){
		window.location.href='index.php';
	}		
	else{
		alert(jsonObj.data);
	}
		
		
}




function verity_authenticated() 
{
	var oObject = {} ;
					
	oObject["component"] = "user";
	oObject["controller"] = "user";
	oObject["task"] = "status";
	
	
	var jsonVales	=	convertToJSON(oObject);
									
											
	parameters	=	''+encodeURIComponent(
									convertToStringJSON(jsonVales));
	
	//alert(parameters);
	
	var method='GET';
	
	httpRequest ( method,
					url_API,
					parameters,
					'returnVerity_authenticated');
						
}

function returnVerity_authenticated(jsonObj){
	
	if( jsonObj.status ==1){
	
		
		if(getXPrivateKey()!=1){
			
			window.location.href='home_authenticated.php';
		}else{
			alert("Você precisa definir sua chave privada.");
		}	
	
		
	
	
	
	}else{
		
		setCookie('x-public','', 30);
		
		if(jsonObj.notification !=6)
			alert( jsonObj.data);
	}
		
}


var username='';


function setUsername(jsonObj){
	
	if( jsonObj.status ==1){
		username=jsonObj.data;
		setElementIdValue("username-id", username);
	}else{
		
		alert(jsonObj.data);
		window.location.href='index.php';//alert('problemas '+jsonObj.data);
		
	}
		
		
}


function getUsername() 
{
	
	var oObject = {} ;
					
	oObject["component"] = "user";
	oObject["controller"] = "user";
	oObject["task"] = "username";
	
	
	var jsonVales	=	convertToJSON(oObject);
	
	parameters	=	encodeURIComponent(
									convertToStringJSON(jsonVales));
	
	var method='GET';
	
	httpRequest ( method,
					url_API,
					parameters,
					'setUsername');

}




function setElementIdValue(id, value){
	
	document.getElementById( id ).innerHTML = value;
}



